package com.xdap.keymen.service.punch;

import com.definesys.mpaas.query.MpaasQuery;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.xdap.keymen.entity.*;
import com.xdap.motor.entity.SnowflakeIdWorker;
import com.xdap.motor.vo.ResponseVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class PunchCustomerService extends PunchBaseService{
    private final SnowflakeIdWorker snowflakeIdWorker;
    private final PunchEmployeeService punchEmployeeService;

    private final PunchDeptService punchDeptService;

    private final PunchContactPersonService punchContactPersonService;

    public ResponseVo getCustomerList(Long rv) {
        //为空则到表中取
        if (rv==null) {
            //2=punch_sales_order
            rv=getMaxRvid("punch_sales_client");
        }
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        //每页条数
        int sz=100;
        //页面
        int pg=1;
        //记录总数
        //int maxCount=this.countCustomers(rv);
        int maxCount=1000;
        //log.info("最大记录数maxCount:{}",maxCount);
        //测试，先默认
        //maxCount=10;
        // 计算总页数 (向上取整)
        int totalPages = (int) Math.ceil((double) maxCount / sz);
        for (int currentPage = pg; currentPage <= totalPages; currentPage++) {
            headers=new HashMap<>();
            headers.put("Authorization", "Bearer "+getPunchToken());
            String response = okHttpUtils.doGet(punchConfig.getUrl().concat("/CRM/api/Customer/")+rv.toString()+"/"+sz+"/"+currentPage, params,headers);
            PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());

            List<PunchSalesClientResponseEntity> list = gson.fromJson(punchResponse.getResult(), new TypeToken<List<PunchSalesClientResponseEntity>>(){}.getType());
            for(PunchSalesClientResponseEntity punchSalesClientResponseEntity:list){
                saveOrUpdateCustomer(punchSalesClientResponseEntity);
                //unchSalesClientResponseEntity);

                //saveOrUpdateCustomerContact(punchSalesClientResponseEntity);
            }

            // 如果已经是最后一页，退出循环
            if (currentPage == totalPages) {
                break;
            }
        }

        return ResponseVo.ok().setData(maxCount);
    }

    private void saveOrUpdateCustomer(PunchSalesClientResponseEntity punchSalesClientResponseEntity) {
        String strSalesBackOffice=removeSpaces(punchSalesClientResponseEntity.getIn_saler());
        PunchEmployeeEntity salesBackOffice = punchEmployeeService.getUserByGonghao(strSalesBackOffice);
        String strSalesBackOfficeName="";
        if(salesBackOffice!=null){
            strSalesBackOfficeName=salesBackOffice.getUsername();
        }
        String strSalesExecutive=removeSpaces(punchSalesClientResponseEntity.getSlsman());
        PunchEmployeeEntity salesExecutive = punchEmployeeService.getUserByGonghao(strSalesExecutive);
        String strSalesExecutiveName="";
        if(salesExecutive!=null){
            strSalesExecutiveName=salesExecutive.getUsername();
        }
        PunchXdapDepartmentsEntity deptEntity=punchDeptService.getPunchXadpDept(removeSpaces(punchSalesClientResponseEntity.getFnumber()));
        String deptId="";
        if(deptEntity!=null){
            deptId=deptEntity.getId();
        }
        String strDocumentId="";
        String custNum=removeSpaces(punchSalesClientResponseEntity.getCust_num());
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.sql("select * from punch_sales_client where client_number='"+removeSpaces(punchSalesClientResponseEntity.getCust_num())+"'");
        PunchSalesClientEntity punchSalesClientEntity= query.doQueryFirst(PunchSalesClientEntity.class);
        if (punchSalesClientEntity!=null) {
            strDocumentId=punchSalesClientEntity.getDocumentId();
            //更新
            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
            query.update("client_name",removeSpaces(punchSalesClientResponseEntity.getName()));
            query.update("client_grade",removeSpaces(punchSalesClientResponseEntity.getCust_grade()));
            query.update("corporate_nature",removeSpaces(punchSalesClientResponseEntity.getCorporate_nature()));
            query.update("client_number",custNum);
            query.update("client_type",removeSpaces(punchSalesClientResponseEntity.getCust_type()));
            query.update("affiliated_industry",removeSpaces(punchSalesClientResponseEntity.getSuoshuhangye()));
            query.update("affiliated_business_office","[\""+deptId+"\"]");
            query.update("located_region",removeSpaces(punchSalesClientResponseEntity.getRegion_code()));
            query.update("locked_status",convertBooleanToChinese(removeSpaces(punchSalesClientResponseEntity.getLock())));
            query.update("sales_back_office",strSalesBackOffice);
            query.update("sales_back_office_renyuan",strSalesBackOfficeName);
            query.update("sales_executive",strSalesExecutive);
            query.update("sales_executive_name",strSalesExecutiveName);
            query.update("file_creation_time",removeSpaces(punchSalesClientResponseEntity.getCreate_date()));
            query.update("reg_addr",removeSpaces(punchSalesClientResponseEntity.getReg_addr()));
            query.update("rvid",punchSalesClientResponseEntity.getRvid());
            query.eq("id", punchSalesClientEntity.getId());
            query.doUpdate(PunchSalesClientEntity.class);
        }else{
            try{
                strDocumentId=snowflakeIdWorker.nextId();
                PunchSalesClientEntity entity = new PunchSalesClientEntity();
                entity.setId(snowflakeIdWorker.nextId());
                entity.setDocumentId(strDocumentId);
                entity.setClientName(removeSpaces(punchSalesClientResponseEntity.getName()));
                entity.setClientGrade(removeSpaces(punchSalesClientResponseEntity.getCust_grade()));
                entity.setCorporateNature(removeSpaces(punchSalesClientResponseEntity.getCorporate_nature()));
                entity.setClientNumber(custNum);
                entity.setClientType(removeSpaces(punchSalesClientResponseEntity.getCust_type()));
                entity.setAffiliatedIndustry(removeSpaces(punchSalesClientResponseEntity.getSuoshuhangye()));
                entity.setAffiliatedBusinessOffice("[\""+deptId+"\"]");
                entity.setLocatedRegion(removeSpaces(punchSalesClientResponseEntity.getRegion_code()));
                entity.setLockedStatus(convertBooleanToChinese(removeSpaces(punchSalesClientResponseEntity.getLock())));
                entity.setSalesBackOffice(strSalesBackOffice);
                entity.setSalesBackOfficeRenyuan(strSalesBackOfficeName);
                entity.setSalesExecutive(strSalesExecutive);
                entity.setSalesExecutiveName(strSalesExecutiveName);
                entity.setFileCreationTime(removeSpaces(punchSalesClientResponseEntity.getCreate_date()));
                entity.setRegAddr(removeSpaces(punchSalesClientResponseEntity.getReg_addr()));
                entity.setRvid(punchSalesClientResponseEntity.getRvid());
                query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
                query.doInsert(entity);

            }catch (Exception e){
                log.error("保存客户失败",e);
            }

        }
        try{
            punchContactPersonService.getCustShiptoPerson(custNum,strDocumentId);
        }catch (Exception e){

        }
        try {
            punchContactPersonService.getCustshiptoinvaddrPerson(custNum,strDocumentId);
        }catch (Exception e){

        }
    }

    /**
     * 客户地址
     * @param punchSalesClientResponseEntity
     */
    private void saveOrUpdateCustomerAddress(PunchSalesClientResponseEntity punchSalesClientResponseEntity) {
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.sql("select id from punch_sales_address where client_number='"+removeSpaces(punchSalesClientResponseEntity.getCust_num())+"'");
        String id= query.doQueryFirst(String.class);
        if (id!=null) {
            //更新
//            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
//            query.update("client_name",punchSalesClientResponseEntity.getContact_co());
//            query.update("rvid",punchSalesClientResponseEntity.getRvid());
//            query.eq("client_number", punchSalesClientResponseEntity.getCust_num());
//            query.doUpdate(PunchSalesClientEntity.class);
        }else{
            //新增
            PunchSalesAddressEntity entity = new PunchSalesAddressEntity();
            entity.setId(snowflakeIdWorker.nextId());
            entity.setDocumentId(snowflakeIdWorker.nextId());
            entity.setClientName(punchSalesClientResponseEntity.getName());
            entity.setClientNumber(punchSalesClientResponseEntity.getCust_num());
            entity.setAddress(punchSalesClientResponseEntity.getReg_addr());
            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
            query.doInsert(entity);
        }

    }

    /**
     * 客户联系人
     * @param punchSalesClientResponseEntity
     */
    private void saveOrUpdateCustomerContact(PunchSalesClientResponseEntity punchSalesClientResponseEntity) {
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.sql("select id from punch_sales_contact where client_number="+punchSalesClientResponseEntity.getCust_num() +" and contact_name="+punchSalesClientResponseEntity.getCust_num());
        String id= query.doQueryFirst(String.class);
        if (id!=null) {
            //更新
//            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
//            query.update("client_name",punchSalesClientResponseEntity.getContact_co());
//            query.update("rvid",punchSalesClientResponseEntity.getRvid());
//            query.eq("client_number", punchSalesClientResponseEntity.getCust_num());
//            query.doUpdate(PunchSalesContactEntity.class);
        }else{
            //新增
//            PunchSalesContactEntity entity = new PunchSalesContactEntity();
//            entity.setId(snowflakeIdWorker.nextId());
//            entity.setDocumentId(snowflakeIdWorker.nextId());
//            entity.setContactName(punchSalesClientResponseEntity.getContact_co());
//
//            entity.setClientName(punchSalesClientResponseEntity.getName());
//            entity.setClientNumber(punchSalesClientResponseEntity.getCust_num());
//
//            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
//            query.doInsert(entity);
        }

    }

    public int countCustomers(Long rv) {
        int count=0;
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        String response = okHttpUtils.doGet(punchConfig.getUrl().concat("/CRM/api/Customer/Count/"+rv.toString()), params,headers);
        PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
        count=Integer.parseInt(punchResponse.getResult());
        return count;
    }

    /**
     * 根据客户编号，获取客户
     * @param customerNumber
     * @return
     */
    public PunchSalesClientEntity getCustomerByNumber(String customerNumber){
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.sql("select * from punch_sales_client where client_number='"+customerNumber+"'");
        PunchSalesClientEntity entity= query.doQueryFirst(PunchSalesClientEntity.class);
        return entity;
    }
}
